﻿using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Threading;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using TVideo.ViewModel;
using Wpf.Ui.Mvvm.Contracts;
using Wpf.Ui.Mvvm.Services;

namespace TVideo
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private static IHost _host = Host.CreateDefaultBuilder().ConfigureAppConfiguration(c =>
            {
                c.SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly()!.Location));
            }).ConfigureServices(ConfigureServices).Build();

        public App()
        {
            this.DispatcherUnhandledException += App_DispatcherUnhandledException;
        }

        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {

        }

        protected override async void OnStartup(StartupEventArgs e)
        {
            await _host.StartAsync();
        }

        protected override async void OnExit(ExitEventArgs e)
        {
            await _host.StopAsync();

            _host.Dispose();
        }

        public static T? GetService<T>() where T : class
        {
            return _host.Services.GetService(typeof(T)) as T;
        }

        private static void ConfigureServices(HostBuilderContext context, IServiceCollection services)
        {
            // Theme manipulation
            services.AddSingleton<IThemeService, ThemeService>();
            services.AddSingleton<ITaskBarService, TaskBarService>();
            services.AddSingleton<ISnackbarService, SnackbarService>();
            services.AddSingleton<IDialogService, DialogService>();
            //services.AddSingleton<INavigationService, NavigationService>();

            services.AddSingleton<IPageService, PageService>();

            services.AddHostedService<ApplicationHostService>();
            //services.AddSingleton<INotifyIconService, CustomNotifyIconService>();

            services.AddScoped<MainWindow>();
            services.AddScoped<MainViewModel>();

            services.AddScoped<View.BrowserPage>();
            services.AddScoped<BrowserViewModel>();
        }
    }
}
